#pragma once

#include "CircuitQueue.h"
class  RecvBuffer
{
public:
	 RecvBuffer() {m_pQueue = NULL;}
	~ RecvBuffer() { if (m_pQueue) delete m_pQueue;}

	void Create(size_t nBufferSize, size_t nExtraSize)
	{
		m_pQueue = new CircuitQueue<unsigned char>();
		m_pQueue->Create(nBufferSize, nExtraSize);
	}

	void Completion(size_t nBytesRecvd)
	{
		m_pQueue->Enqueue(NULL, nBytesRecvd);
	}
 
	void GetRecvParam(unsigned char** pRecvPtr, size_t& nLen)
	{
		*pRecvPtr = m_pQueue->GetWritePtr(nLen);
	}

	unsigned char* GetFirstPacketPtr(size_t nMaxPacketSize)
	{
		PacketHeader header;

		if (m_pQueue->Peek((unsigned char*)&header, sizeof(PacketHeader)) == false)
		{
			return NULL;
		}

		if ((header.m_nLength <= 4) && (header.m_nLength > nMaxPacketSize))
		{
			return NULL;
		}

		size_t nPacketLength = header.m_nLength + sizeof(header.m_nLength);
		if (m_pQueue->GetLength()  < nPacketLength)
		{
			return NULL;
		}

		if (m_pQueue->GetBackDataCount() < nPacketLength)
		{
			m_pQueue->CopyHeadDataToExtraBuffer(nPacketLength - m_pQueue->GetBackDataCount());
		}

		unsigned char* pByte = m_pQueue->GetReadPtr(nPacketLength);
		return pByte;
	}

	void RemoveFirstPacket(size_t nSize)
	{
		m_pQueue->Dequeue(NULL, nSize);
	}
private:
	CircuitQueue<unsigned char>* m_pQueue;
};

 